package com.zhou.app.favourite.security;

import com.zhou.app.favourite.cache.LoginFailRetryNumGuavaCache;
import com.zhou.app.favourite.entity.SysUser;
import com.zhou.app.favourite.security.model.MyUserDetails;
import com.zhou.app.favourite.service.impl.SysUserServiceImpl;
import com.zhou.common.lib.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * Security 加载用户信息服务
 * <p>
 * @serial 2.0.0
 * @author 就眠儀式
 */
@Slf4j
@Component
public class SecureUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        int failCount = LoginFailRetryNumGuavaCache.getcount(username);
        if (failCount >= 5) {
            throw new LockedException("登录失败超过5次，请30分粥再重新登录");
        }

        SysUser sysUser = sysUserService.loadUserByUsername(username);
        //todo 查询角色，查询权限，查询组织
        if (sysUser == null) {
            throw new UsernameNotFoundException(StringUtils.format("Username {} not found", username));
        }

        MyUserDetails userDetails = new MyUserDetails(sysUser);
        return userDetails;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        log.info(passwordEncoder.encode("QQZX@qqonline1234"));
    }

}
